package com.dobbyspringside.modules.tools;

import com.dobbyspringside.modules.utils.Exceptions;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.DefaultResourceLoader;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
 * Created by liguoqing on 2016/3/1.
 */
public class Freemarkers {


    /**
     * 渲染模板字符数
     */
    public static String renderString(String templateString,Map<String,?> model) {

        StringWriter stringWriter = new StringWriter();
        try {
            Template template = new Template("default", new StringReader(templateString),new Configuration());
            template.process(model,stringWriter);
            return stringWriter.toString();

        } catch (Exception e) {
            throw Exceptions.unchecked(e);
        }
    }


    /**
     * 渲染template文件
     */
    public static String renderTemplate(Template template, Object model) {
        StringWriter stringWriter = new StringWriter();
        try {
            template.process(model,stringWriter);
            return stringWriter.toString();

        } catch (Exception e) {
            throw  Exceptions.unchecked(e);
        }
    }


    /**
     * 创建默认配置，设定模板目录
     * @param directory
     * @return
     */
    public static Configuration buildConfiguration(String directory) throws IOException {

        Configuration configuration = new Configuration();
        org.springframework.core.io.Resource path = new DefaultResourceLoader().getResource(directory);
        configuration.setDirectoryForTemplateLoading(path.getFile());
        return configuration;

    }

}
